package com.study.base.io.nio.demo.noblock;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by tan on 2017/7/17.
 */
public class NIOServer {
	private ServerSocketChannel serverSocketChannel;
	private Selector selector;

	public NIOServer(int port) throws IOException {
		//创建ServerSocketChannel
		serverSocketChannel = ServerSocketChannel.open();
		//ServerSocketChannel绑定端口
		//这两种方式有什么区别?
		//serverSocketChannel.socket().bind(new InetSocketAddress(port));
		serverSocketChannel.bind(new InetSocketAddress(port));
		//配置为非阻塞模式 默认为true
		serverSocketChannel.configureBlocking(false);


		selector = Selector.open();
		SelectionKey key = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
	}

	public void start() {
		while (true) {
			try {
				int num = selector.select();
				Set<SelectionKey> keys = selector.selectedKeys();
				Iterator<SelectionKey> it = keys.iterator();
				while (it.hasNext()) {
					SelectionKey key = it.next();
					it.remove();
					//deal
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) throws IOException {
		NIOServer nioServer = new NIOServer(89);
		nioServer.start();
	}
}
